// pages/order/paymentorder/paymentorder.js
const app = new getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    Base: '',
    defaultImg: {},
    order_top_image: [1,2,3,4,5],
    order_tag: '',
    order_goods_type: '',
    order_sku_list: '',
    cart_list: '',
    coupon_list: {},
    discount_money: 0.00,
    express_company_list: {},
    goods_list: {},
    member_account: {},
    member_address: {},
    order_total_money: {},
    pick_up_money: 0.00,
    promotion_full_mail: {},
    goods_sku_list: '',
    pay_money: 0.00, //应付金额
    mask_status: '', //遮罩层
    pay_box_status: 0, //支付方式弹框
    delivery_status: 0, //配送方式弹框
    delivery_type: 1, //配送方式
    coupon_status: 0, //优惠券弹框
    use_coupon: 0, //优惠券
    coupon_money: 0.00, //优惠券金额
    integral: 0, //积分
    leavemessage: '', //留言
    balance: 0.00, //使用余额
    pay_type: 0, //支付方式
    order_invoice_money: 0.00, //发票税额
    invoice_status: 0, //发票弹框
    invoice_need: 0, //是否需要发票
    invoice_title: '', //发票抬头
    taxpayer_identification_number: '', //纳税人识别号
    invoice_content_status: 0, //发票内容弹框
    invoice_content: '', //发票内容
    pick_up_status: 0, //自提点弹框
    pick_up: 0, //自提点id,
    pick_up_point: '', //自提点
    pick_up_money: 0.00, //自提点运费
    express_company_status: 0, //物流公司弹框
    shipping_company_id: 0, //物流公司id
    express_company: '', //物流公司
    express_money: 0.00, //物流运费
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let tag = options.tag;
    let base = app.globalData.siteBaseUrl;
    let defaultImg = app.globalData.defaultImg;

    if(tag == 1){
      tag = 'buy_now';
      let sku = options.sku;
      let goods_type = options.goods_type;

      that.setData({
        order_goods_type: goods_type,
        order_sku_list: sku,
      })
    }else if(tag == 2){
      tag = 'cart';
      let cart_list = options.cart_list
      
      that.setData({
        cart_list: cart_list
      })
    }else{
      app.showBox(that, '无法获取订单信息');
      wx.navigateBack({
        delta: 1
      })
    }

    that.setData({
      Base: base,
      order_tag: tag,
      defaultImg: defaultImg,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    let pay_money = that.data.pay_money;
    let order_tag = that.data.order_tag;
    let order_goods_type = that.data.order_goods_type;
    let order_sku_list = that.data.order_sku_list;
    let cart_list = that.data.cart_list;
    let coupon_money = parseFloat(that.data.coupon_money);

    let parm = {
      order_tag: order_tag
    };

    if (order_tag == 'buy_now'){
      parm.order_goods_type = order_goods_type;
      parm.order_sku_list = order_sku_list;
    } else if (order_tag == 'cart'){
      parm.cart_list = cart_list;
    }else{
      app.showBox(that, '无法获取订单信息');
      wx.navigateBack({
        delta: 1
      })
      return false;
    }

    app.sendRequest({
      url: 'api.php?s=order/getOrderData',
      data: parm,
      success: function (res) {
        let code = res.code;
        let data = res.data;

        if (code == 0) {
          let discount_money = parseFloat(data.discount_money) + coupon_money;
          let balance = parseFloat(that.data.balance);
          let new_pay_money = parseFloat(data.count_money) + parseFloat(data.express) - discount_money - balance;
          pay_money = parseFloat(pay_money) > 0 ? pay_money : new_pay_money;
          let shipping_company_id = that.data.shipping_company_id;
          let express_company = that.data.express_company;
          let express_company_list = data.express_company_list;
;
          //选中默认物流
          if (parseInt(data.express_company_count) > 0 && shipping_company_id == 0 && data.express_company_list[0] != undefined){
            for (let index in express_company_list){
              if (express_company_list[index].is_default == 1){
                shipping_company_id = express_company_list[index].co_id;
                express_company = data.express_company_list[index].company_name;
              }
            }
            
            if (shipping_company_id == 0 && parseInt(data.express_company_count) > 0 && data.express_company_list[0] != undefined){
              shipping_company_id = express_company_list[0].co_id;
              express_company = express_company_list[0].company_name;
            }
          }
          
          that.setData({
            order_info: data,
            goods_sku_list: data.goods_sku_list,
            pay_money: parseFloat(pay_money).toFixed(2),
            coupon_list: data.coupon_list,
            discount_money: parseFloat(discount_money).toFixed(2),
            express_company_list: express_company_list,
            shipping_company_id: shipping_company_id,
            express_company: express_company,
            itemlist: data.itemlist,
            member_account: data.member_account,
            member_address: data.address_default,
            count_money: parseFloat(data.count_money).toFixed(2),
            express_money: parseFloat(data.express).toFixed(2),
            pick_up_money: parseFloat(data.pick_up_money).toFixed(2),
            promotion_full_mail: data.promotion_full_mail,
            shop_config: data.shop_config,
          })
        }
        console.log(res);
      }

    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 图片加载失败
   */
  errorImg: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let defaultImg = that.data.defaultImg;
    let parm = {};

    if (defaultImg.is_use == 1) {
      let parm_key = "itemlist[" + index + "].picture_info.pic_cover_small";
      parm[parm_key] = defaultImg.value.default_goods_img;

      that.setData(parm);
    }
  },

  /**
   * 收货地址
   */
  myAddress: function(event) {
    wx.navigateTo({
      url: '/pages/member/memberaddress/memberaddress'
    })
  },

  /**
   * 支付方式
   */
  payType: function(event){
    let that = this;
    let status = event.currentTarget.dataset.status;

    that.setData({
      pay_box_status: status,
      mask_status: status
    })
  },

  /**
   * 选择支付方式
   */
  selectPayType: function(e){
    let that = this;
    let pay_type = e.currentTarget.dataset.flag;
    let delivery_type = that.data.delivery_type;
    delivery_type = pay_type == 0 ? delivery_type : 1;
    let coupon_money = parseFloat(that.data.coupon_money);
    let order_info = that.data.order_info;
    let express = delivery_type == 1 ? parseFloat(that.data.express_money) : parseFloat(that.data.pick_up_money); //运费
    let discount_money = parseFloat(order_info.discount_money); //优惠金额
    let count_money = parseFloat(order_info.count_money); //商品总价
    let balance = parseFloat(that.data.balance);

    discount_money = discount_money + coupon_money;
    let pay_money = count_money + express - discount_money - balance;
    let order_invoice_tax = parseFloat(that.data.shop_config.order_invoice_tax); //发票税率
    let invoice_need = that.data.invoice_need; //是否需要发票
    let order_invoice_money = invoice_need == 1 ? order_invoice_tax / 100 * pay_money : 0.00;
    pay_money = parseFloat(order_invoice_money) + parseFloat(pay_money);
    pay_money = pay_money.toFixed(2);

    that.setData({
      pay_type: pay_type,
      delivery_type: delivery_type,
      order_invoice_money: parseFloat(order_invoice_money).toFixed(2),
      pay_money: pay_money
    })
    that.closePoupo();
  },

  /**
   * 配送方式
   */
  deliveryType: function(event){
    let that = this;
    let status = event.currentTarget.dataset.status;

    that.setData({
      delivery_status: status,
      mask_status: status
    })
  },

  /**
   * 选择配送方式
   */
  deliveryTypeSelect: function (e){
    let that = this;
    let status = e.currentTarget.dataset.status;
    let coupon_money = parseFloat(that.data.coupon_money);
    let order_info = that.data.order_info;
    let express = status == 1 ? parseFloat(that.data.express_money) : parseFloat(that.data.pick_up_money); //运费
    let discount_money = parseFloat(order_info.discount_money); //优惠金额
    let count_money = parseFloat(order_info.count_money); //商品总价
    let balance = parseFloat(that.data.balance);

    discount_money = discount_money + coupon_money;
    let pay_money = count_money + express - discount_money - balance;
    
    if(status == 2){
      let point_list = that.data.order_info.pickup_point_list.data;
      let pick_up = point_list[0] == undefined ? 0 : point_list[0].id;
      let pick_up_point = point_list[0] == undefined ? '' : point_list[0].province_name + '　' + point_list[0].city_name + '　' + point_list[0].dictrict_name + '　' + point_list[0].address;

      that.setData({
        pick_up: pick_up,
        pick_up_point: pick_up_point
      })
    }

    let order_invoice_tax = parseFloat(that.data.shop_config.order_invoice_tax); //发票税率
    let invoice_need = that.data.invoice_need; //是否需要发票
    let order_invoice_money = invoice_need == 1 ? order_invoice_tax / 100 * pay_money : 0.00;
    pay_money = parseFloat(order_invoice_money) + parseFloat(pay_money);
    pay_money = pay_money.toFixed(2);

    that.setData({
      delivery_type: status,
      order_invoice_money: parseFloat(order_invoice_money).toFixed(2),
      pay_money: pay_money
    })
    that.closePoupo();
  },

  /**
   * 物流公司
   */
  expressCompany: function(e){
    let that = this;
    
    that.setData({
      express_company_status: 1,
      mask_status: 1
    })
  },

  /**
   * 选择物流公司
   */
  selectExpressCompany: function(e){
    let that = this;
    let data = e.currentTarget.dataset;
    let express_money = data.fee;
    let shipping_company_id = data.id; 
    let express_company = data.name;
    let coupon_money = that.data.coupon_money // 优惠券金额
    let order_info = that.data.order_info; //待付款订单信息
    let discount_money = parseFloat(order_info.discount_money); //优惠金额
    let count_money = parseFloat(order_info.count_money); //商品总价
    let balance = parseFloat(that.data.balance);

    discount_money = discount_money + coupon_money;
    let pay_money = count_money + express_money - discount_money - balance;
    let order_invoice_tax = parseFloat(that.data.shop_config.order_invoice_tax); //发票税率
    let invoice_need = that.data.invoice_need; //是否需要发票
    let order_invoice_money = invoice_need == 1 ? order_invoice_tax / 100 * pay_money : 0.00;
    pay_money = parseFloat(order_invoice_money) + parseFloat(pay_money);
    pay_money = pay_money.toFixed(2);

    that.setData({
      express_money: parseFloat(express_money).toFixed(2),
      shipping_company_id: shipping_company_id,
      express_company: express_company,
      order_invoice_money: parseFloat(order_invoice_money).toFixed(2),
      pay_money: pay_money
    })
    that.closePoupo();
  },

  /**
   * 优惠券
   */
  couponStatus: function(e){
    let that = this;

    that.setData({
      coupon_status: 1,
      mask_status: 1
    })
  },

  /**
   * 选择优惠券
   */
  selectCoupon: function(e){
    let that = this;
    let id = e.currentTarget.dataset.id;
    let coupon_money = parseFloat(e.currentTarget.dataset.money); // 优惠券金额
    let order_info = that.data.order_info; //待付款订单信息
    let delivery_type = that.data.delivery_type; //配送方式
    let express = delivery_type == 1 ? parseFloat(that.data.express_money) : parseFloat(that.data.pick_up_money); //运费
    let discount_money = parseFloat(order_info.discount_money); //优惠金额
    let count_money = parseFloat(order_info.count_money); //商品总价
    let balance = parseFloat(that.data.balance);
    
    discount_money = discount_money + coupon_money;
    let pay_money = count_money + express - discount_money - balance;
    let order_invoice_tax = parseFloat(that.data.shop_config.order_invoice_tax); //发票税率
    let invoice_need = that.data.invoice_need; //是否需要发票
    let order_invoice_money = invoice_need == 1 ? order_invoice_tax / 100 * pay_money : 0.00;
    pay_money = parseFloat(order_invoice_money) + parseFloat(pay_money);
    pay_money = pay_money.toFixed(2);

    that.setData({
      use_coupon: id,
      coupon_money: parseFloat(coupon_money).toFixed(2),
      order_invoice_money: parseFloat(order_invoice_money).toFixed(2),
      pay_money: pay_money,
      discount_money: parseFloat(discount_money).toFixed(2),
    })
    that.closePoupo();
  },

  /**
   * 自提地址
   */
  pickUp: function(e){
    let that = this;


    that.setData({
      pick_up_status: 1,
      mask_status: 1,
    })
  },

  /**
   * 选择自提地址
   */
  pickUpSelect: function(e){
    let that = this;
    let data = e.currentTarget.dataset;
    let pick_up = data.id;
    console.log(data)
    let province = data.province;
    let city = data.city;
    let disctrict = data.disctrict;
    let address = data.address;
    let pick_up_point = province + '　' + city + '　' + disctrict + '　' + address;
    
    that.setData({
      pick_up: pick_up,
      pick_up_point: pick_up_point
    })

    that.closePoupo();
  },

  /**
   * 发票
   */
  invoiceType: function(e){
    let that = this;

    that.setData({
      invoice_status: 1,
      mask_status: 1
    })
  },

  /**
   * 选择是否需要发票
   */
  selectInvoice: function(e){
    let that = this;
    let status = e.currentTarget.dataset.status;
    let order_invoice_content_list = that.data.shop_config.order_invoice_content_list;
    let order_info = that.data.order_info; //待付款订单信息
    let delivery_type = that.data.delivery_type; //配送方式
    let coupon_money = that.data.coupon_money // 优惠券金额
    let express = delivery_type == 1 ? parseFloat(that.data.express_money) : parseFloat(that.data.pick_up_money); //运费
    let discount_money = parseFloat(order_info.discount_money); //优惠金额
    let count_money = parseFloat(order_info.count_money); //商品总价
    let balance = parseFloat(that.data.balance);

    discount_money = discount_money + coupon_money;
    let pay_money = count_money + express - discount_money - balance;
    let order_invoice_tax = parseFloat(that.data.shop_config.order_invoice_tax); //发票税率
    let order_invoice_money = status == 1 ? order_invoice_tax / 100 * pay_money : 0.00;
    pay_money = parseFloat(order_invoice_money) + parseFloat(pay_money);
    pay_money = pay_money.toFixed(2);
    order_invoice_money = parseFloat(order_invoice_money).toFixed(2)

    that.setData({
      invoice_need: status,
      invoice_content: order_invoice_content_list[0],
      order_invoice_money: parseFloat(order_invoice_money).toFixed(2),
      pay_money: pay_money,
    })

    that.closePoupo();
  },

  /**
   * 发票内容
   */
  invoiceContent: function(e){
    let that = this;

    that.setData({
      invoice_content_status: 1,
      mask_status: 1
    })
  },

  /**
   * 选择发票内容
   */
  selectInvoiceContent: function(e){
    let that = this;
    let content = e.currentTarget.dataset.content;

    that.setData({
      invoice_content: content
    })

    that.closePoupo();
  },

  /**
   * 关闭弹框
   */
  closePoupo: function(e){
    let that = this;
    
    that.setData({
      mask_status: 0, //遮罩层
      pay_box_status: 0, //支付方式弹框
      delivery_status: 0, //配送方式弹框
      coupon_status: 0, //优惠券弹框
      pick_up_status: 0, //自提点弹框
      express_company_status: 0, //物流公司弹框
      invoice_status: 0, //发票弹框
      invoice_content_status: 0, //发票内容弹框
    })
  },

  /**
   * 余额输入
   */
  inputBalance: function(event){
    let that = this;
    let balance = event.detail.value;
    let max_balance = parseFloat(event.currentTarget.dataset.max);
    
    let delivery_type = that.data.delivery_type; //配送方式
    let express = delivery_type == 1 ? parseFloat(that.data.express_money) : parseFloat(that.data.pick_up_money); //运费
    let coupon_money = that.data.coupon_money // 优惠券金额
    let order_info = that.data.order_info; //待付款订单信息
    let discount_money = parseFloat(order_info.discount_money); //优惠金额
    let count_money = parseFloat(order_info.count_money); //商品总价
    discount_money = discount_money + coupon_money;
    let order_invoice_tax = parseFloat(that.data.shop_config.order_invoice_tax); //发票税率
    let invoice_need = that.data.invoice_need; //是否需要发票
    let pay_money = count_money + express - discount_money;
    let order_invoice_money = invoice_need == 1 ? order_invoice_tax / 100 * pay_money : 0.00;
    pay_money = parseFloat(order_invoice_money) + parseFloat(pay_money);
    pay_money = pay_money.toFixed(2);
    console.log(pay_money)

    balance = balance == '' ? 0.00 : balance;
    balance = parseFloat(balance).toFixed(2);
    balance = isNaN(balance) ? 0.00 : balance;

    if (balance <= 0.01 && balance > 0){
      balance = 0.00;
      app.showBox(that, '余额输入错误');
    }

    if(balance > max_balance){
      balance = max_balance
      app.showBox(that, '不能超过可用余额！');
    }

    if (pay_money - balance < 0){
      balance = pay_money
      pay_money = 0.00;
    }else{
      pay_money = pay_money - balance;
    }

    that.setData({
      balance: balance,
      pay_money: pay_money
    })
    return balance;
  },

  /**
   * 发票抬头输入
   */
  inputInvoiceTitle: function(e){
    let that = this;
    let title = e.detail.value;

    that.setData({
      invoice_title: title
    })
  },

  /**
   * 纳税人识别号输入
   */
  inputTaxpayerIdentificationNumber: function(e){
    let that = this;
    let identification_number = e.detail.value;

    that.setData({
      taxpayer_identification_number: identification_number
    })
  },

  /**
   * 留言输入
   */
  inputMessage: function(e){
    let that = this;
    let leavemessage = e.detail.value;

    that.setData({
      leavemessage: leavemessage
    })
  },

  /**
   * 提交订单
   */
  commitOrder: function(event) {
    let that = this;
    let goods_sku_list = that.data.goods_sku_list; //商品列表
    let delivery_type = that.data.delivery_type; //配送方式
    let use_coupon = that.data.use_coupon; //优惠券
    let integral = that.data.integral; //积分
    let leavemessage = that.data.leavemessage; //留言
    let account_balance = that.data.balance; //使用余额
    let pay_type = that.data.pay_type; //支付方式
    let pick_up_id = that.data.pick_up; //自提点,
    let shipping_company_id = that.data.shipping_company_id; //物流公司
    let invoice_need = that.data.invoice_need; //是否需要发票
    let invoice_title = that.data.invoice_title; //发票抬头
    let taxpayer_identification_number = that.data.taxpayer_identification_number; //纳税人识别号
    let invoice_content = that.data.invoice_content; //发票内容
    let buyer_invoice = invoice_title + '$' + invoice_content + '$' + taxpayer_identification_number; //发票
    buyer_invoice = invoice_need == 1 ? buyer_invoice : '';
    let member_address = that.data.member_address;
    let pay_money = that.data.pay_money;

    if (member_address == '' || member_address == null){
      app.showBox(that, '请先选择收货地址');
      return false;
    }

    if (delivery_type == 1){
      
    }else{
      if (pick_up_id == 0){
        app.showBox(that, '商家未配置自提点，请选择其他配送方式');
        return false;
      }
    }

    if (invoice_need == 1 && invoice_title == ''){
      app.showBox(that, '请输入发票抬头');
      return false;
    }

    pay_type = pay_money == 0 ? 5 : pay_type;

    app.sendRequest({
      url: 'api.php?s=order/orderCreate',
      data: {
        use_coupon: use_coupon,
        integral: integral,
        goods_sku_list: goods_sku_list,
        leavemessage: leavemessage,
        account_balance: account_balance,
        pay_type: pay_type,
        buyer_invoice: buyer_invoice,
        pick_up_id: pick_up_id,
        shipping_company_id: shipping_company_id,
      },
      success: function (res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (pay_type == 5){
            let out_trade_no = data.out_trade_no;
            wx.reLaunch({
              url: '/pages/pay/paycallback/paycallback?status=1&out_trade_no=' + out_trade_no,
            })
          }else{
            wx.redirectTo({
              url: '/pages/pay/getpayvalue/getpayvalue?out_trade_no=' + data.out_trade_no
            })
          }
        }
        console.log(res)
      }
    })

  },

})